/*
 * @Author: chengsl
 * @Date: 2022-11-03 15:04:11
 * @LastEditors: chengsl
 * @LastEditTime: 2022-11-30 17:35:16
 * @Description: 公用方法
 */

//将url中的参数转成对象的形式
const urlParamsToObj = function (str) {
  arr = str.split('&')
  let objResult = {}
  for (let i = 0; i < arr.length; i++) {
    let key = arr[i].split('=')[0]
    let value = arr[i].split('=')[1]
    objResult[key] = value
  }
  return objResult
}

//增加换行打印的好看点
const getResultStr = function (result) {
  let str = ''
  result.forEach((item, index) => {
    str += `\n${index}:  ${JSON.stringify(item)}`
  })
  return str
}

/**
 * 将错误信息转换为字符串的格式
 * 有些报错 通过JSON.stringify 转回报错，进而导致服务挂掉，这里尽量兼容各错误情况
 */
const errorToString = function (error) {
  try {
    if (typeof error === 'string') {
      return error
    } else {
      try {
        return JSON.stringify(error)
      } catch (error) {
        try {
          return error.toSring()
        } catch (error) {
          return ''
        }
      }
    }
  } catch (error) {
    return ''
  }
}

/**
 * 返回当前格式化时间
 */
var dayjs = require('dayjs')
const NOW_TIME = function () {
  return dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
}
const NOW_DATE = function () {
  return dayjs(new Date()).format('YYYY-MM-DD')
}

/**
 * 将对象转换成驼峰格式
 */
function getObjectFormat(obj) {
  for (let key in obj) {
    if (key.includes('_')) {
      const arr = key.split('_')
      arr.forEach((item, index) => {
        if (index > 0) {
          arr[index] = item[0].toUpperCase() + item.substr(1)
        }
      })
      const newKey = arr.join('')
      obj[newKey] = obj[key]
      delete obj[key]
    }
  }
  return obj
}

/**
 * 将sql查询的结果 转换为 指定类的对象集合
 * @param {*} data 数据集
 * @param {*} originClass 想要转换成对象的类
 * @returns
 */
function getIWantObjectListByClass(data, originClass) {
  const result = []
  data.forEach(item => {
    result.push(new originClass(getObjectFormat(item)))
  })
  return result
}

/**
 * 根据对象 生产对象类的代码
 * @param {*} obj 与该类结构一致的对象
 */
 function getClassDtoByObject(obj, calssName = 'MyClass') {
  let oneCodeBlock = ''
  let twoCodeBlock = ''
  let threeCodeBlock = ''
  const keyArr = Object.keys(obj)
  oneCodeBlock = keyArr.join(', ')
  keyArr.forEach(key=>{
    twoCodeBlock += `this.${key} = ${key}\n`
    threeCodeBlock += `set${key[0].toUpperCase() + key.substr(1)}(val){
      this.${key} = val
      return this
    }\n`
  })
  return code = 
  `class ${calssName} {
    constructor({ ${oneCodeBlock} } = {}) {
      ${twoCodeBlock}
    }
    ${threeCodeBlock}\n
    toString() {
      return JSON.stringify(this)
    }
  }\n
  module.exports = {
    ${calssName}
  }\n`
}

module.exports = {
  urlParamsToObj,
  getResultStr,
  errorToString,
  NOW_TIME,
  NOW_DATE,
  getIWantObjectListByClass,
  getClassDtoByObject
}
